package oss.ngocminh.fw.dao;

import java.util.ArrayList;
import java.util.List;
import oss.ngocminh.fw.data.Thread;

import android.content.ContentValues;
import android.database.Cursor;

public class ThreadDAO {

	private static final String TABLE_NAME = "thread";
	private static final String ID = "_ID";
	private static final String TITLE = "title";
	private static final String BASE_URL = "base_url";
	private static final String THREAD_ID = "thread_id";
	private static final String PAGE_COUNT = "page_count";
	private DatabaseHelper db;

	public ThreadDAO(DatabaseHelper db) {
		super();
		this.db = db;
	}

	public Thread findById(int id) {
		Cursor result = db.getReadableDatabase().query(TABLE_NAME, new String[] {
				ID, TITLE, BASE_URL, THREAD_ID, PAGE_COUNT
		}, ID + "=?", new String[] { String.valueOf(id) }, null, null, null);
		List<Thread> threads = toThreads(result);
		result.close();
		return threads.size() == 1 ? threads.get(0) : null;
	}

	private List<Thread> toThreads(Cursor result) {
		List<Thread> threads = new ArrayList<Thread>();
		while (result.moveToNext()) {
			threads.add(new Thread(result.getLong(0), result.getString(1),
					result.getString(2), result.getString(3), result.getInt(4)));
		}
		return threads;
	}

	public void saveOrUpdate(Thread thread) {
		if (thread.getId() == null) {
			save(thread);
		} else {
			update(thread);
		}
	}

	public void update(Thread thread) {
		ContentValues cv = new ContentValues();
		cv.put(BASE_URL, thread.getBaseUrl());
		cv.put(THREAD_ID, thread.getThreadId());
		cv.put(TITLE, thread.getTitle());
		cv.put(PAGE_COUNT, thread.getPageCount());
		db.getWritableDatabase().update(TABLE_NAME, cv, ID + "=?", 
				new String[] { String.valueOf(thread.getId())});
	}

	public void save(Thread thread) {
		ContentValues cv = new ContentValues();
		cv.put(BASE_URL, thread.getBaseUrl());
		cv.put(THREAD_ID, thread.getThreadId());
		cv.put(TITLE, thread.getTitle());
		cv.put(PAGE_COUNT, thread.getPageCount());
		long id = db.getWritableDatabase().insert(TABLE_NAME, "", cv);
		thread.setId(id);
	}
	
}
